package client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import util.Log;

public class NettyEchoClient {
    private int serverPort;
    private String serverIp;
    private Bootstrap bootstrap;

    public NettyEchoClient(String serverIp, int serverPort) {
        this.serverPort = serverPort;
        this.serverIp = serverIp;
        this.bootstrap = new Bootstrap();
    }

    public void start() {

        EventLoopGroup workerLoopGroup = new NioEventLoopGroup();
        try {
            bootstrap.group(workerLoopGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.remoteAddress(serverIp, serverPort);
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new NettyEchoClientHandler());
                }
            });

            ChannelFuture channelFuture = bootstrap.connect();
            channelFuture.addListener((ChannelFutureListener) cf -> {
                if (cf.isSuccess()) {
                    Log.i("客户端连接成功");
                } else {
                    Log.i("客户端连接失败");
                }
            });
            channelFuture.sync();
            Channel channel = channelFuture.channel();
            ByteBuf byteBuf = channel.alloc().buffer();
            byteBuf.writeBytes("hello i an client".getBytes());
            channel.writeAndFlush(byteBuf);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerLoopGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new NettyEchoClient("127.0.0.1", 6666).start();
    }
}
